package com.czwx.bee.business.manager.config.security;

import cn.hutool.core.util.StrUtil;
import com.czwx.bee.base.common.dto.ResponseDto;
import com.czwx.bee.base.common.exception.BizExceptionEnum;
import com.czwx.bee.base.web.support.HttpKit;
import com.czwx.bee.business.manager.modular.sys.model.SecurityUser;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * JWT过滤器
 * 
 * @author Wiki
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	private final Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Value("${jwt.header}")
	private String tokenHeader;

	@Value("${jwt.refresh}")
	private Long refresh;

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		final String authToken = request.getHeader(this.tokenHeader);
		String username = null;
		if (!StrUtil.isEmpty(authToken)) {
			try {
				username = jwtTokenUtil.getUsernameFromToken(authToken);
			} catch (IllegalArgumentException e) {
				HttpKit.responseJson(response,new ResponseDto(BizExceptionEnum.LOGIN_TOKEN_FAILED));
				return;
			} catch (ExpiredJwtException e) {

			}
			catch (JwtException exception){
				HttpKit.responseJson(response,new ResponseDto(BizExceptionEnum.LOGIN_TOKEN_FAILED));
				return;
			}
		}

		if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
			UserDetails userDetails = null;

			userDetails = (SecurityUser) redisTemplate.opsForValue().get("token:"+authToken);

			// 判断是否需要刷新token
			if (null != userDetails) {
				Long expire = redisTemplate.getExpire("token:"+authToken, TimeUnit.SECONDS);
				if (expire > 0 && expire < (refresh / 2)) {
					redisTemplate.expire("token:"+authToken, refresh, TimeUnit.SECONDS);
				}

				if(jwtTokenUtil.validateToken(authToken, userDetails)){
					UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
							userDetails, null, userDetails.getAuthorities());
					authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
					SecurityContextHolder.getContext().setAuthentication(authentication);
					logger.info("authenticated cloanuser " + username + ", setting security context");
				}
			}else {
				HttpKit.responseJson(response,new ResponseDto(BizExceptionEnum.LOGIN_TOKEN_FAILED));
				return;
			}
		}
		chain.doFilter(request, response);
	}

}